package com.party.core.service.competition.biz;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.competition.CompetitionSchedule;
import com.party.core.service.competition.ICompetitionScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.List;

/**
 * 赛事日程业务处理
 * Created by yifeng
 *
 * @date 2018/4/16 0016
 * @time 下午 14:07
 */
@Service
public class CompetitionScheduleBizService {
    @Autowired
    private ICompetitionScheduleService competitionScheduleService;

    /**
     * 赛事日程业务处理
     *
     * @param projectId 项目id
     * @param schedules 赛事日程集合
     */
    public void saveScheduleBiz(String projectId, List<CompetitionSchedule> schedules, String memberId) throws ParseException {
        List<String> newScheduleIds = Lists.newArrayList();
        for (CompetitionSchedule schedule : schedules) {
            schedule.setUpdateBy(memberId);
            if (StringUtils.isNotEmpty(schedule.getPlayDayStr())) {
                schedule.setPlayDay(DateUtils.parse(schedule.getPlayDayStr(), "yyyy-MM-dd HH:mm"));
            }
            if (StringUtils.isEmpty(schedule.getId())) {
                schedule.setProjectId(projectId);
                schedule.setCreateBy(memberId);
                schedule.setOpenStatus(YesNoStatus.YES.getCode());
                schedule.setResultNum(0);
                competitionScheduleService.insert(schedule);
            } else {
                competitionScheduleService.update(schedule);
            }
            newScheduleIds.add(schedule.getId());
        }
        List<CompetitionSchedule> oldSchedules = competitionScheduleService.findByProject(projectId);
        List<String> oldScheduleIds = LangUtils.transform(oldSchedules, new Function<CompetitionSchedule, String>() {
            @Override
            public String apply(CompetitionSchedule input) {
                return input.getId();
            }
        });
        oldScheduleIds.removeAll(newScheduleIds);

        for (String scheduleId : oldScheduleIds) {
            competitionScheduleService.delete(scheduleId);
        }
    }
}
